package org.example.util;

import org.example.dao.CategoryDAO;
import org.example.dao.RecordDAO;
import org.example.entity.Category;
import org.example.entity.Record;
import org.knowm.xchart.CategoryChart;
import org.knowm.xchart.CategoryChartBuilder;
import org.knowm.xchart.PieChart;
import org.knowm.xchart.PieChartBuilder;
import org.knowm.xchart.style.Styler;

import java.util.ArrayList;
import java.util.List;


public class ChartUtil {
    /**
     * 获取柱状图
     */
    public static CategoryChart getCategoryChart() {
        // 统计图数据
        List<Record> recordList = RecordDAO.statisticData();
        List<String> xData = new ArrayList<>();
        List<Double> yData = new ArrayList<>();
        for (int i = 0; i < recordList.size(); i++) {
            if (i % 5 == 0) {
                xData.add(i + 1 + "日");
            } else {
                xData.add(" ");
            }
            yData.add(recordList.get(i).getSpend());
        }


        // 绘制统计图
        CategoryChart chart =
                new CategoryChartBuilder()
                        .width(400)
                        .height(400)
                        .title("当月消费 - 按日统计")
                        .xAxisTitle("日期(日)")
                        .yAxisTitle("消费金额(元)")
                        .theme(Styler.ChartTheme.GGPlot2)
                        .build();
        chart.getStyler().setLegendVisible(false);
        chart.getStyler().setLabelsVisible(false);
        chart.getStyler().setPlotGridLinesVisible(false);
        chart.addSeries("每日消费", xData, yData);
        return chart;
    }


    /**
     * 获取扇形图
     */
    public static PieChart getPieChart() {
        // 绘制统计图
        PieChart chart =
                new PieChartBuilder()
                        .width(400)
                        .height(400)
                        .title("当月消费 - 按消费分类统计")
                        .theme(Styler.ChartTheme.GGPlot2)
                        .build();
        chart.getStyler().setLegendVisible(false);
        chart.getStyler().setLabelsDistance(1.15);
        chart.getStyler().setPlotContentSize(.7);
        chart.getStyler().setStartAngleInDegrees(90);

        // 给扇形图添加数据
        List<Category> categoryList = CategoryDAO.statisticData();
        for (Category category : categoryList) {
            chart.addSeries(category.getName(), category.getRecordTotalSpend());
        }

        return chart;
    }
}
